package bb.lanxing.adapter.team;

import android.content.Context;
import android.net.Uri;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import java.util.ArrayList;
import java.util.List;

import bb.lanxing.R;

public class TeamImageCreateAdapter extends RecyclerView.Adapter<TeamImageCreateAdapter.ViewHolder> {
    public static final int TYPE_ITEM = 1;
    public static final int TYPE_ADD = 2;
    private List<String> allList = new ArrayList<>();
    private OnItemClickListener listener;
    private RemoveListener removeListener;
    private Context mContext;

    public class ViewHolder extends RecyclerView.ViewHolder {
        ImageView image;
        ImageView del_iv;

        public ViewHolder(@NonNull View itemView) {
            super(itemView);
            image = itemView.findViewById(R.id.image);
            del_iv = itemView.findViewById(R.id.del_iv);
        }
    }

    public interface OnItemClickListener {
        void onItemClick(int position);
    }

    public interface RemoveListener {
        void remove(int position);
    }

    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        mContext = parent.getContext();
        View view = LayoutInflater.from(mContext).inflate(R.layout.item_team_image, parent, false);
        return new ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
        holder.itemView.setOnClickListener(v -> {
            if (listener != null) {
                listener.onItemClick(position);
            }
        });
        if (TYPE_ITEM == getItemViewType(position)) {
            holder.image.setImageURI(Uri.parse(allList.get(position)));
            holder.del_iv.setOnClickListener(v -> {
                if (removeListener != null) {
                    removeListener.remove(position);
                }
            });
        } else {
            holder.del_iv.setVisibility(View.GONE);
        }
    }

    @Override
    public int getItemViewType(int position) {
        if ("".equals(allList.get(position))) {
            return TYPE_ADD;
        } else {
            return TYPE_ITEM;
        }
    }

    @Override
    public int getItemCount() {
        return allList.size();
    }

    public void setOnItemClickListener(OnItemClickListener listener) {
        this.listener = listener;
    }

    public void setRemoveListener(RemoveListener listener) {
        removeListener = listener;
    }

    public void updateData(List<String> dataList) {
        // 加入最后的十字添加
        allList = new ArrayList<>();
        allList.addAll(dataList);
        if (dataList.size() < 4) {
            allList.add("");
        }
        notifyDataSetChanged();
    }
}